package com.ledim.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import com.ledim.activity.MainActivity;
import com.ledim.activity.SearchActivity;
import com.ledim.adapter.CardA1PageAdapter;
import com.ledim.adapter.ChoiceCardAdapter;
import com.ledim.adapter.base.LedimBaseListAdapter;
import com.ledim.adapter.base.LoopPagerAdapter;
import com.ledim.app.LeDimApplication;
import com.ledim.bean.LedimCardGroupBean;
import com.ledim.bean.LedimGroupsCardReponse;
import com.ledim.datastatistics.LeDimAnalysisUtils;
import com.ledim.fragment.base.LedimBaseListFragment;
import com.ledim.itf.LedimDoubleClickListener;
import com.ledim.service.ApiService;
import com.ledim.service.LedimApiServiceFactory;
import com.ledim.service.LedimHttpObserver;
import com.ledim.utils.ConstantUtil;
import com.ledim.utils.DensityUtil;
import com.ledim.utils.LogUtil;
import com.ledim.widget.view.LedimChoiceListView;
import com.ledim.widget.viewPager.LoopViewPager;
import com.ledim.widget.viewPager.transformer.HomePageTransformer;
import com.letv.android.young.client.R;
import com.letv.tracker2.enums.EventType;
import com.letv.tracker2.enums.Key;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by ccx on 16/7/26.
 * 首页精选Fragment
 */
public class LedimChoiceFragment extends LedimBaseListFragment
        implements MainActivity.DoubleTabClickLister, LedimChoiceListView.ChoiceListViewListener {

    private LedimChoiceListView listView;
    private View mBannerView;
    private LoopViewPager mViewPager;
    private Subscription subscription;
    private rx.Observer mObsevers;

    @Override
    protected LedimBaseListAdapter getAdapter() {
        return new ChoiceCardAdapter(getBaseActivity());
    }

    @Override
    protected void getDatas() {
        if (mObsevers == null) {
            mObsevers = new LedimHttpObserver<LedimGroupsCardReponse>() {
                @Override
                public void onCompleted() {
                    super.onCompleted();
                }

                @Override
                public void onError(Throwable e) {
                    super.onError(e);
                    setServerDataError();
                    LogUtil.e("getDatas====" + e.getMessage());
                }

                @Override
                public void onNext(LedimGroupsCardReponse reponse) {
                    if (reponse != null && reponse.success) {
                        initTotalPages(reponse.paged.total);
                        List<LedimCardGroupBean> result = new ArrayList<LedimCardGroupBean>();
                        if (reponse.data != null && reponse.data.size() > 0) {
                            for (LedimCardGroupBean cardGroupdBean : reponse.data) {
                                if (cardGroupdBean.style == ConstantUtil.CardGroupStyle.card1) {
                                    if (mBannerView == null) {
                                        mBannerView = getBaseActivity().getLayoutInflater()
                                                                       .inflate(R.layout.card_a1_list, null);
                                        listView.addHeaderView(mBannerView);
                                        if (mAdapter != null) {
                                            ((ChoiceCardAdapter) mAdapter).mCardIds.put(cardGroupdBean.id, "1");
                                        }
                                    }
                                    setBannerViewData(cardGroupdBean);
                                } else {
                                    if (cardGroupdBean.style == ConstantUtil.CardGroupStyle.card2 ||
                                            cardGroupdBean.style ==
                                                    ConstantUtil.CardGroupStyle.card3 ||
                                            cardGroupdBean.style ==
                                                    ConstantUtil.CardGroupStyle.card4 ||
                                            cardGroupdBean.style ==
                                                    ConstantUtil.CardGroupStyle.card5 ||
                                            cardGroupdBean.style ==
                                                    ConstantUtil.CardGroupStyle.card6 ||
                                            cardGroupdBean.style ==
                                                    ConstantUtil.CardGroupStyle.card7 ||
                                            cardGroupdBean.style ==
                                                    ConstantUtil.CardGroupStyle.card8 ||
                                            cardGroupdBean.style ==
                                                    ConstantUtil.CardGroupStyle.card9) {
                                        result.add(cardGroupdBean);
                                    }
                                }
                            }
                        }
                        setDatas(result, reponse.paged.more);
                        listView.setPullLoadEnable(reponse.paged.more);
                    } else {
                        setServerDataError();
                    }
                }
            };
        }

        subscription = LedimApiServiceFactory.createService(ApiService.class)
                                             .getChoicePageGroups(mLoadPage +
                                                     1, getPageSize(), LeDimApplication.getInstance()
                                                                                       .getAppVersionName())
                                             .observeOn(AndroidSchedulers.mainThread())
                                             .subscribeOn(Schedulers.io())
                                             .subscribe(mObsevers);
    }

    /**
     * @param cardGroup
     */
    public void setBannerViewData(LedimCardGroupBean cardGroup) {
        mViewPager = (LoopViewPager) mBannerView.findViewById(R.id.card_a1_list_pager);
        //mViewPager.setNestedpParent((ViewGroup) v);
        mViewPager.setPageMargin(DensityUtil.dip2px(mActivity, 7));

        if (cardGroup != null && cardGroup.cards != null && cardGroup.cards.size() > 0) {
            CardA1PageAdapter pageAdapter =
                    new CardA1PageAdapter(mActivity, cardGroup.cards, cardGroup.id);
            mViewPager.setAdapter(new LoopPagerAdapter(pageAdapter));
            if (cardGroup.cards != null && cardGroup.cards.size() > 1) {
                mViewPager.setCurrentItem(cardGroup.cards.size() * 100 + 1);
                mViewPager.setOffscreenPageLimit(3);
                mViewPager.startMove();
                mViewPager.setPageTransformer(true, new HomePageTransformer());
            }

        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mViewPager != null) {
            mViewPager.destroy();
        }
        if (subscription != null) {
            subscription.unsubscribe();
        }
    }

    @Override
    protected void initContentView(View view, Bundle saveInstanceState) {
        LogUtil.e("ccx initContentView");
        listView = ((LedimChoiceListView) mAdapterView);
        view.findViewById(R.id.tv_choice).setOnTouchListener(new LedimDoubleClickListener() {

            @Override
            public void onDoubleClick(View view) {
                listView.setSelection(0);
                listView.setSelectionAfterHeaderView();
                listView.smoothScrollToPosition(0);
            }
        });

        listView.setListViewListener(this);
        view.findViewById(R.id.iv_choice_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("buttonName", "search");
                LeDimAnalysisUtils.reportEvent(LeDimAnalysisUtils.CHOICE_PAGE_CODE, EventType.Click, params);
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
            }
        });
        mAdapter.setOnScrollListener(new AbsListView.OnScrollListener() {

            private boolean mScroll;

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                mScroll = true;
                switch (scrollState) {

                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        mScroll = false;
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                                 int totalItemCount) {
                if (firstVisibleItem >= 1) {
                    if (mViewPager != null) {
                        mViewPager.stopMove();
                    }
                } else {
                    if (mViewPager != null && !mScroll) {
                        mViewPager.startMove();
                    }
                }
            }
        });

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_ledim_choice;
    }

    @Override
    public void onTabDoubleClick() {
        if (mAdapterView != null) {
            pullRefresh();
        }
    }

    /**
     * 上传曝光事件
     */
    private void reportExpose() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put(Key.Type.name(), "homepage");
        LeDimAnalysisUtils.reportEvent(LeDimAnalysisUtils.CHOICE_PAGE_CODE, EventType.Expose, params);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isHidden()) {
            reportExpose();
            if (mViewPager != null) {
                mViewPager.startMove();
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        if (hidden) {
            if (getAdapter() != null) {
                ((ChoiceCardAdapter) mAdapter).postCardExposeEvent();
            }
            if (mViewPager != null) {
                mViewPager.stopMove();
            }
        } else {
            reportExpose();
            if (mViewPager != null) {
                mViewPager.startMove();
            }
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        //上传卡片曝光统计事件
        if (!isHidden() && getAdapter() != null) {
            ((ChoiceCardAdapter) mAdapter).postCardExposeEvent();
        }
        if (mViewPager != null) {
            mViewPager.stopMove();
        }
    }

    @Override
    public void onStartLoadMore() {
        loadMore();
    }
}
